'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
    console.log('开始执行每日佣金结算定时任务...');
    const now = Date.now();

    // 查找所有激活日期已到且佣金待激活的订单
    // activation_date 是订单完成时间 + 7天
    const ordersToSettle = await db.collection('orders').where({
        status: 'completed',
        commission_status: 'pending',
        activation_date: dbCmd.lte(now)
    }).get();

    if (ordersToSettle.data.length === 0) {
        console.log('没有需要结算的佣金。任务结束。');
        return { settledCount: 0 };
    }

    console.log(`发现 ${ordersToSettle.data.length} 条待结算订单。`);
    let settledCount = 0;

    for (const order of ordersToSettle.data) {
        if (!order.promoter_id || !order.commission_amount || order.commission_amount <= 0) {
            console.log(`订单 ${order._id} 没有推荐人或佣金金额为0，跳过`);
            continue;
        }

        try {
            // ✅ 修复：阿里云不支持 runTransaction，改为顺序执行
            // a. 更新订单的佣金状态
            await db.collection('orders').doc(order._id).update({
                commission_status: 'activated',
                commission_activated_time: now,
                activation_countdown: 0
            });

            // b. 转移推广者钱包金额（从待激活到可提现）
            await db.collection('users').doc(order.promoter_id).update({
                commission_pending: dbCmd.inc(-order.commission_amount),
                commission_available: dbCmd.inc(order.commission_amount),
                commission_total: dbCmd.inc(order.commission_amount)
            });

            settledCount++;
            console.log(`✅ 订单 ${order._id} 的佣金 ${order.commission_amount} 分已激活，转入推广者 ${order.promoter_id} 的可提现余额`);
        } catch (e) {
            console.error(`❌ 结算订单 ${order._id} 失败:`, e);
        }
    }

    console.log(`成功结算 ${settledCount} 条订单。任务结束。`);
    return { settledCount };
};